package top.mcwebsite.playandroid.common.webview

import android.net.http.SslError
import android.util.Log
import android.webkit.SslErrorHandler
import android.webkit.WebResourceRequest
import android.webkit.WebView
import android.webkit.WebViewClient
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.rounded.ArrowBack
import androidx.compose.material.icons.rounded.MoreHoriz
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import com.google.accompanist.web.LoadingState
import com.google.accompanist.web.WebView
import com.google.accompanist.web.WebViewState
import com.google.accompanist.web.rememberWebViewNavigator
import com.google.accompanist.web.rememberWebViewState
import kotlinx.coroutines.flow.Flow

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun EasyWebView(
    url: String,
    webViewState: WebViewState = rememberWebViewState(url = url),
    onClickBack: () -> Unit,
    onClickMore: () -> Unit,
    actionFlow: Flow<WebViewAction>,
    content: @Composable () -> Unit,
) {

    Scaffold(
        topBar = {
            TopAppBar(
                navigationIcon = {
                    IconButton(onClick = { onClickBack() }) {
                        Icon(imageVector = Icons.Rounded.ArrowBack, contentDescription = null)
                    }
                },
                title = {
                    Text(text = webViewState.pageTitle ?: "", maxLines = 1, overflow = TextOverflow.Ellipsis)
                },
                actions = {
                    IconButton(onClick = { onClickMore() }) {
                        Icon(imageVector = Icons.Rounded.MoreHoriz, contentDescription = null)
                    }
                })
        }
    ) {
        val webViewNavigator = rememberWebViewNavigator()
        var wm by remember {
            mutableStateOf<WebView?>(null)
        }
        LaunchedEffect(wm) {
            actionFlow.collect {
                when (it) {
                    is WebViewAction.Refresh -> {
                        webViewNavigator.reload()
                    }
                    is WebViewAction.Find -> {
                        wm?.findAllAsync(it.content)
                    }

                    WebViewAction.FindNext -> {
                        wm?.findNext(true)
                    }

                    WebViewAction.FindPre -> {
                        wm?.findNext(false)
                    }

                    WebViewAction.FindClose -> {
                        wm?.clearMatches()
                    }
                }
            }
        }
        Box(modifier = Modifier.padding(it)) {
            WebView(
                modifier = Modifier
                    .fillMaxSize(),
                state = webViewState,
                navigator = webViewNavigator,
                onCreated = { webView ->
                    wm = webView
                    webView.settings.apply {
                        javaScriptEnabled = true
                        domStorageEnabled = true
                    }
                    webView.webViewClient = object : WebViewClient() {
                        override fun onReceivedSslError(view: WebView?, handler: SslErrorHandler?, error: SslError?) {
                            handler?.proceed()
                        }

                        override fun shouldOverrideUrlLoading(view: WebView?, request: WebResourceRequest?): Boolean {
                            view?.loadUrl(url)
                            return true
                        }
                    }
                }
            )
            if (webViewState.loadingState is LoadingState.Loading) {
                Log.d("mengchen", "webView loading = ${(webViewState.loadingState as LoadingState.Loading).progress}")
                LinearProgressIndicator(
                    progress = (webViewState.loadingState as LoadingState.Loading).progress,
                    color = MaterialTheme.colorScheme.primary,
                    trackColor = MaterialTheme.colorScheme.primaryContainer,
                    modifier = Modifier
                        .fillMaxWidth()
                        .height(1.dp)
                )
            }
            content()
        }
    }
}


